# -*- coding: utf-8 -*-

"""
@author: 猿小天
@contact: QQ:1638245306
@Created on: 2021/6/6 006 10:30
@Remark: 自定义权限
"""
import re

from django.contrib.auth.models import AnonymousUser
from rest_framework.permissions import BasePermission

from super.system.models import Menu


def ValidationApi(reqApi, validApi):
    """
    验证当前用户是否有接口权限
    :param reqApi: 当前请求的接口
    :param validApi: 用于验证的接口
    :return: True或者False
    """
    if validApi is not None:
        valid_api = validApi.replace('{id}', '.*?')
        matchObj = re.match(valid_api, reqApi, re.M | re.I)
        if matchObj:
            return True
        else:
            return False
    else:
        return False


class AnonymousUserPermission(BasePermission):
    """
    匿名用户权限
    """

    def has_permission(self, request, view):
        if isinstance(request.user, AnonymousUser):
            return False
        return True


def replace_uuid(api):
    """
    将接口的uuid替换掉
    :param api:
    :return:
    """
    pattern = re.compile(r'[a-f\d]{4}(?:[a-f\d]{4}-){4}[a-f\d]{12}/$')
    m = pattern.search(api)
    if m:
        res = api.replace(m.group(0), "{id}/")
        return res
    else:
        return api


class CustomPermission(BasePermission):
    """自定义权限"""

    def has_permission(self, request, view):
        if isinstance(request.user, AnonymousUser):
            return False

        # 判断是否是超级管理员
        if request.user.is_superuser:
            return True
        else:
            menu_id = request.query_params.get('menu_id')
            if menu_id:
                menus = Menu.objects.filter(id=menu_id)
                if menus.exists():
                    menu = menus[0]

                    if menu.creator == request.user:
                        return True
            api = request.path  # 当前请求接口
            method = request.method  # 当前请求方法
            method_list = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
            method = method_list.index(method)
            # ***接口白名单***
            # url = ReUUID(api)
            # if url:
            #     apiWhiteList_instance = ApiWhiteList.objects.filter(url__regex=url, method=method).first()
            #     if apiWhiteList_instance:
            #         return True
            # ********#
            if not hasattr(request.user, "role"):
                return False
            user_api_list = request.user.role.values('permission__api', 'permission__method')  # 获取当前用户的角色拥有的所有接口
            return self.is_permission(user_api_list, api, method)

    @classmethod
    def is_permission(cls, user_api_list, api, method):
        url = replace_uuid(api)
        path = f'{url}:{method}'
        user_api_list = [f'{item["permission__api"]}:{item["permission__method"]}' for item in user_api_list]
        return path in user_api_list















